<template>
  <div class="outer">
    <!-- 这是search模块 -->
    <TypeNav />
    <ListContent
      :goodsList="goodsList"
      :searchParams="searchParams"
      :getSearchData="getSearchData"
      @trademarkInfo="trademarkInfo"
      @attrInfo="attrInfo"
      :pageNo="pageNo"
      :pageSize="pageSize"
      :totalPages="totalPages"
    />

    <Toolbar />
  </div>
</template>
<script>
import ListContent from '@/pages/Search/ListContent'
import Toolbar from '@/pages/Search/Toolbar'

import { mapGetters } from 'vuex'
export default {
  name: 'Search',
  // props: ['keywords'],
  data() {
    return {
      // 带给服务器的参数
      searchParams: {
        category1Id: '',
        category2Id: '',
        category3Id: '',
        categoryName: '',
        keyword: '',
        props: [],
        trademark: '',
        order: '1:desc', //初始默认综合且降序
        pageNo: 1,
        pageSize: 3,
        totalPages: 91,
        continues: 5,
      },
    }
  },
  provide() {
    return {
      pageNo: this.searchParams.pageNo,
      pageSize: this.searchParams.pageSize,
      totalPages: this.searchParams.totalPages,
      continues: this.searchParams.continues,
    }
  },
  components: {
    ListContent,
    Toolbar,
  },
  beforeMount() {
    // 当组件挂载完毕之前执行一次
    // console.log('@', this.$route.query)
    Object.assign(this.searchParams, this.$route.query, this.$route.params)
  },
  mounted() {
    // 在发请求之前带给服务器参数【searchParams参数发生变化有数值带给服务】
    this.getSearchData()
  },
  computed: {
    // mapGetters 里面的写法：传递的数组，因为getters计算的是没有划分模块的
    ...mapGetters(['goodsList']),
  },
  methods: {
    // 向服务器发送请求获取search模块的数据，（根据参数不同返回不同的数据进行展示）
    // 把这次请求封装成一个函数：当你需要调用的时候调用
    getSearchData() {
      this.$store.dispatch('getSearchList', this.searchParams)
    },
    trademarkInfo(trademark) {
      this.searchParams.trademark = `${trademark.tmId}:${trademark.tmName}`
      this.getSearchData()
    },
    attrInfo(attr, attrValue) {
      // 收集平台属性的地方回调函数
      let props = `${attr.attrId}:${attrValue}:${attr.attrName}`
      // 数组去重
      if (this.searchParams.props.indexOf(props) == -1) {
        this.searchParams.props.push(props)
      }
      this.getSearchData()
    },
  },
  watch: {
    // 监听路由的信息是否发生变化，如果发生变化，再次发送请求
    $route(newValue, oldValue) {
      // 再次发请求之前整理带给服务器的数据
      Object.assign(this.searchParams, this.$route.query, this.$route.params)
      this.getSearchData()
      // 每一次请求完毕，应该把相应的id，清除
      this.searchParams.category1Id = undefined
      this.searchParams.category2Id = undefined
      this.searchParams.category3Id = undefined

      // console.log(this.searchParams)
    },
  },
}
</script>
<style lang="less" scoped></style>
